//
//  AppDelegate.m
//  Translate
//
//  Created by will on 14/12/24.
//  Copyright (c) 2014年 Pinguo. All rights reserved.
//

#import "AppDelegate.h"

#import "GWFileAcceptImageView.h"
#import "GWFileTool.h"
#import "GWExecuteTool.h"
#import "GWDSYMFile.h"
#import "GWCrashFile.h"

@interface AppDelegate () <GWFileAcceptImageViewDelegate>

@property (weak) IBOutlet NSTextField *mTextField;
@property (strong) NSMutableDictionary *mSuccessTrans;

/**  用于接收拖拽进来的文件 */
@property (weak) IBOutlet GWFileAcceptImageView *fileAcceptImageView;
@property (weak) IBOutlet NSWindow *window;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application

}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
    
    return YES;
}


#pragma mark - FileAcceptImageView 代理方法
- (void)dragDropViewFileList:(NSArray *)fileList
{
    self.mSuccessTrans = [NSMutableDictionary dictionary];
    self.mTextField.stringValue = @"转换成功：\n";
    [self.mTextField setHidden:YES];
    
    __unsafe_unretained AppDelegate *weakSelf = self;
    
    [GWFileTool filePathsWithArray:fileList succes:^(GWFiles *files) {
        NSMutableArray *crashFiles = [NSMutableArray arrayWithArray:files.crashFilePaths];
        NSArray *dSYMPaths = files.dSYMFilePaths;
        
        NSLog(@"=====crash文件路径: %@",crashFiles);
        NSLog(@"=====dSYM文件路径: %@",dSYMPaths);
        
        // 转换crash文件
        [weakSelf symbolCrashPaths:crashFiles dsymPaths:dSYMPaths];
        
        //
        //        if (crashFiles.count)
        //        {
        //            NSAlert *alert = [[NSAlert alloc] init];
        //            NSString *text = [NSString stringWithFormat:@"无法解析以下crash文件,没有对于的dsym文件\n%@",crashFiles];
        //            [alert setMessageText:text];
        //            [alert runModal];
        //        }
        
        
        
    } failure:^(NSString *error) {
        
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:[NSString stringWithFormat:@"%@ ! ",error]];
        [alert runModal];
        return ;
    }];
    
}

- (void)symbolCrashPaths:(NSArray *)crashPaths dsymPaths:(NSArray *)dsympaths
{
    __unsafe_unretained AppDelegate *weakSelf = self;
    for (NSString *dsym in dsympaths)
    {
        for (NSString *crash in crashPaths)
        {
            [weakSelf SingleSymbolCrashPath:crash dsymPaths:dsym];
        }
    }
}

- (void)SingleSymbolCrashPath:(NSString *)crashpath dsymPaths:(NSString *)dsymPath
{
    __unsafe_unretained AppDelegate *weakSelf = self;
    [GWExecuteTool fetchCrashModelWithCrashPath:crashpath dSYMPath:dsymPath success:^(GWCrashFile *crash) {
        
        // 判断crash文件与dsym文件是否匹配
        if (!crash.isMatchDsymUUID)
        {
            return ;
        }
        // 记录下匹配成功的文件
        weakSelf.mSuccessTrans[dsymPath] = crash.path;
        
        
         __unsafe_unretained GWCrashFile *cf = crash;
        [GWExecuteTool symbolMemoryWithDsymPath:dsymPath arch:cf.arch address:cf.memoryDictSrc.allKeys success:^(NSDictionary *symbolDict) {
            
            
            for (NSString *memoryShort in cf.memoryDictSrc.allKeys)
            {
                NSString *memoryLong = cf.memoryDictSrc[memoryShort];
                memoryLong = [memoryLong substringToIndex:46];
                NSString *symbolMemory = symbolDict[memoryShort];
                memoryLong =  [memoryShort stringByAppendingFormat:@" %@",symbolMemory];
                NSString *cutString = [NSString stringWithFormat:@"(in %@) ",cf.trueName];
                memoryLong = [memoryLong stringByReplacingOccurrencesOfString:cutString withString:@""];
                cf.content = [cf.content stringByReplacingOccurrencesOfString:memoryShort withString:memoryLong];
            }
            
            NSString *newFilePath = [[crash.path stringByDeletingPathExtension] stringByAppendingString:@"_trans.crash"];
            NSFileManager *fm = [NSFileManager defaultManager];
            NSData *data = [cf.content dataUsingEncoding:NSUTF8StringEncoding];
            [fm removeItemAtPath:newFilePath error:nil];
            BOOL isWrite = [fm createFileAtPath:newFilePath contents:data attributes:nil];
            if (!isWrite) {
                NSAlert *alert =  [NSAlert alertWithMessageText:@"失败" defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"生成的文件失败"];
                [alert runModal];
            }
            else
            {
                NSAlert *alert =  [NSAlert alertWithMessageText:@"成功" defaultButton:nil alternateButton:nil otherButton:nil informativeTextWithFormat:@"转换文件成功！请查看当前目录！"];
                //                [alert runModal];
                
                //                for (NSString *dsym in self.mSuccessTrans.allKeys)
                //                {
                //                    NSString *crash = self.mSuccessTrans[dsym];
                //                    NSString *match = [NSString stringWithFormat:@"%@ 匹配 %@\n",crash,dsym];
                //                }
                NSString *match = [NSString stringWithFormat:@"%@%@ 匹配 %@\n",self.mTextField.stringValue,dsymPath,cf.path];
                weakSelf.mTextField.stringValue = match;
                [weakSelf.mTextField setHidden:NO];
            }
            
            
            
            
        } failure:^(NSString *error) {
            
        }];
        
        
    } failure:^(NSString *error) {
        
    }];
}

@end
